<template>
  <div>
    <Card
      title="批量新增-供货信息"
      :bordered="false"
      dis-hover
      class="ivu-mt i-table-no-border"
    >
      <Row class="card-title" justify="start" type="flex" style="margin: 10px">
        <supply @getName="getSupply" isAuth="1"></supply>
        <Row style="display: flex">
          <span style="margin-left: 30px; width: 180px"
            >供应商主营品类：{{ topsupply.main }}</span
          >
          <span style="margin-left: 30px; width: 180px"
            >供应商管理区域：{{ topsupply.area }}</span
          >
          <!--<span style="margin-left: 30px;width: 180px;">供货计量单位</span>-->
        </Row>
      </Row>
      <Row class="action_bar_wrap" justify="end" type="flex">
        <Col v-if="showBtn('关联商品')">
          <el-button
            class="action_bar_btn_color"
            type="text"
            @click="handleAssociatedGoods"
            >关联商品</el-button
          >
        </Col>
        <Col v-if="showBtn('导出') && specTableData.length > 0">
          <el-button
            class="action_bar_btn_color"
            type="text"
            @click="handleExportData"
            :loading="exportLoading"
          >
            模板导出
          </el-button>
        </Col>
        <Col v-if="showBtn('导入')">
          <a>
            <Upload
              class="action_bar_upload"
              :show-upload-list="false"
              :format="['xlsx', 'xls', 'csv']"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :on-format-error="handleUploadFormatError"
              :before-upload="handleBeforeUpload"
              :data="uploadData"
              :action="
                uploadBaseURL + 'sysback/supplyskurel/importTemplateForCreate'
              "
              >模板导入
            </Upload>
          </a>
        </Col>
        <Col v-if="specTableData.length > 0">
          <el-button
            class="action_bar_btn_color"
            type="text"
            @click="handleSubmitData"
            :loading="submitLoading"
            >提交
          </el-button>
        </Col>
      </Row>
      <Row class="format_table_wrap">
        <skus-table
          :loading="tableLoading"
          :data-source="specTableData"
          :columns="columns1"
        />
      </Row>
    </Card>
    <associated-goods-modal
      ref="link"
      :columns="associatedGoodsTableColumns"
      :requestApi="requestApi"
      :requestParams="requestParams"
      :distinctParams="distinctParams"
      associatedSkuIdName="skuCode"
      @submitAction="getAssociatedGoodsAction"
      :pageSizeOpts="[10, 50, 100, 500, 1000]"
    ></associated-goods-modal>
  </div>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
/* components */
import supply from '@/components/commodity/getSupply.vue';
import SkusTable from '@/components/skusTable';
import associatedGoodsModal from '@/components/common/dialog/associatedGoods/associatedGoodsDialog';
/* mixins */
import skuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/skuDimension';
/* constants */
import { requiredParamsOther } from '@/components/common/dialog/associatedGoods/constants/skuDimension';
import { ADD_SUPPLY_INFO_AMOUNT } from '@/constants/exportAmountLimit';
/* utils */
import { generateUuid } from '@/utils/bizUtils';

export default {
  mixins: [skuDimensionMixins],
  components: {
    supply,
    associatedGoodsModal,
    SkusTable
  },
  data () {
    return {
      requestApi: {
        url: ['/sysback/sku/list/getFinishSkuList'],
        type: 'post'
      },
      requestParams: [...requiredParamsOther.requestParams],
      distinctParams: requiredParamsOther.distinctParams,
      exportLoading: false, // 导出按钮loading
      submitLoading: false, // 提交按钮loading
      tableLoading: false,
      supplyUuid: '', // 供应商uuid
      specTableData: [], // 供货表格
      uploadData: {
        supplyUuid: ''
      },
      topsupply: {
        main: '',
        area: ''
      },
      associatedGoodsTableColumns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '商品名称',
          key: 'productName',
          minWidth: 120
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          minWidth: 120
        },
        {
          title: '商品分类',
          key: 'categoryPath',
          minWidth: 120
        },
        {
          title: 'SKU编码',
          key: 'skuNo',
          minWidth: 120
        },
        {
          title: '规格参数',
          key: 'specDetailStr',
          minWidth: 120
        },
        {
          title: '品牌',
          key: 'brandName',
          minWidth: 120
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 100
        }
      ],
      columns1: [
        { title: '商品名称', key: 'productName', minWidth: 150 },
        { title: '商品类型', key: 'productTypeStr', minWidth: 150 },
        { title: 'SKU编码', key: 'skuNo', minWidth: 150 },
        { title: '规格', key: 'specDetailStr', minWidth: 150 },
        {
          title: '厂家商品代码',
          key: 'factoryCode',
          align: 'center',
          width: 160,
          type: 'input'
        },
        {
          title: '厂家商品名称',
          key: 'factoryName',
          align: 'center',
          width: 160,
          type: 'input'
        },
        /* {
          title: '采购面价',
          slot: 'purchasePrice',
          align: 'center',
          minWidth: 150
        }, */
        {
          title: '最小订货量',
          key: 'minOrderGoodsNum',
          align: 'center',
          width: 160,
          type: 'inputNum'
        },
        {
          title: '是否保修',
          key: 'warrantyStatus',
          align: 'center',
          type: 'select',
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '2' }
          ]
        },
        {
          title: '保修天数',
          key: 'warrantyDay',
          align: 'center',
          width: 160,
          type: 'inputNum'
        },
        {
          title: '是否可换货',
          key: 'exchangeGoodsStatus',
          align: 'center',
          type: 'select',
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '2' }
          ]
        },
        {
          title: '换货天数',
          key: 'exchangeGoodsDay',
          align: 'center',
          width: 160,
          type: 'inputNum'
        },
        {
          title: '换货条件',
          key: 'exchangeGoodsCondition',
          align: 'center',
          width: 160,
          type: 'input'
        },
        {
          title: '是否可退货',
          key: 'returnGoodsStatus',
          align: 'center',
          type: 'select',
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '2' }
          ]
        },
        {
          title: '退货天数',
          key: 'returnGoodsDay',
          align: 'center',
          width: 160,
          type: 'inputNum'
        },
        {
          title: '退货条件',
          key: 'returnGoodsCondition',
          align: 'center',
          width: 160,
          type: 'input'
        },
        {
          title: '最小退换货量',
          key: 'minReOrExNum',
          align: 'center',
          width: 160,
          type: 'input'
        },
        {
          title: '商品销售最小残品值',
          key: 'minSaleImperfectionsNum',
          width: 180,
          type: 'inputNum'
        },
        { title: '商品包装', key: 'productPacking', width: 150, type: 'input' },
        {
          title: '其他服务承诺',
          key: 'otherPromise',
          width: 160,
          type: 'input'
        }
      ]
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  created () {
    // this.categoryUuid = this.$route.query.categoryUuid;
  },
  mounted () {
    // 刷新页面清除选择的供应商缓存
    window.localStorage.removeItem('selectSupplyList');
  },
  methods: {
    // 获取供应商
    getSupply (row) {
      this.supplyUuid = row.supplierCode;
      this.supplierName = row.supplierName;
      this.uploadData = {
        supplyUuid: this.supplyUuid
      };
      this.topsupply.main = row.supMainCategoryName;
      this.topsupply.area = row.supManagerHrAreaName;
      this.specTableData = []; // 选择供应商后清空表格内容
      this.CLEAR_GOODS(); // 清空关联商品
    },
    // 点击 '选择sku'
    handleAssociatedGoods () {
      if (!this.supplyUuid) {
        return this.$Message.warning('请先选择供应商');
      }
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.requestApi.url = [
        `/sysback/supplyskurel/getNoRelSkuList?supplyUuid=${this.supplyUuid}`,
        `/sysback/supplyskurel/getRelSkuList?supplyUuid=${this.supplyUuid}`
      ];
      this.CHANGE_MODAL_SWITCH(true);
      this.$nextTick(() => {
        this.$refs.link.getDataListAction();
      });
    },
    getAssociatedGoodsAction () {
      let selectedSkuList = this.getSkuNoListFn(
        this.getListFromMapFn(),
        'productUuid'
      );
      if (selectedSkuList.length === 0) {
        this.specTableData = [];
        return;
      }
      let params = {
        productUuids: selectedSkuList.join(',')
      };
      this.tableLoading = true;
      ApiRequest(
        '/sysback/skuaudit/list/getAuditSkuByProducts',
        'post',
        params,
        true
      ).then(res => {
        this.tableLoading = false;
        if (res.retStatus !== '1') {
          return;
        }
        let extraData = {
          minOrderGoodsNum: 0,
          warrantyDay: 0,
          exchangeGoodsDay: 0,
          returnGoodsCondition: 0,
          minReOrExNum: 0,
          minSaleImperfectionsNum: 0
        };
        this.specTableData = res.retData.map(item => ({
          ...item,
          ...extraData
        }));
      }).catch(() => {
        this.tableLoading = false;
      });
    },

    // 导出表格
    handleExportData () {
      let list = [];
      this.specTableData.forEach(function (item, index) {
        list.push(item.skuNo);
      });
      if (this.supplyUuid == '' || this.specTableData == []) {
        return this.$Message.error('请选择供应商或sku');
      }
      let uuid = generateUuid();
      const params = {
        skuNos: list,
        supplyUuid: this.supplyUuid,
        supplyName: this.supplierName,
        uuid
      };
      this.exportLoading = true;
      ApiRequestExportTable(
        '/sysback/supplyskurel/downLoadTemplateForCreate',
        'post',
        params,
        false
      )
        .then(res => {
          this.exportLoading = false;
          const blob = new Blob([res], {
            type: 'application/octet-stream'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = `批量新增-供货信息模板_${uuid}.xlsx`;
          link.click();
          window.URL.revokeObjectURL(blob); // 释放掉blob对象
        })
        .catch(() => {
          this.exportLoading = false;
          this.$Message.error('导出失败');
        });
      /* window.location.href = this.exportBaseURL +
          '/sysback/supplyskurel/downLoadTemplateForCreate?supplyUuid=' + this.supplyUuid + '&skuNos=' +
          skuStr; */
    },

    // 上传格式验证失败
    handleUploadFormatError (file, fileList) {
      this.tableLoading = false;
      this.$Message.error('格式错误');
    },

    // 上传之前
    handleBeforeUpload () {
      this.tableLoading = true;
    },

    // 上传成功
    handleUploadSuccess (res) {
      this.tableLoading = false;
      const { retData, retStatus, retMessage } = res;
      if (retStatus != 1) {
        return this.$Message.error(retMessage || '导入失败');
      }
      this.$Message.success('导入成功');
      this.specTableData = retData;
    },

    // 上传失败
    handleUploadError () {
      this.tableLoading = false;
      this.$Message.error('上传失败');
    },

    // 提交
    handleSubmitData () {
      if (this.specTableData.length > ADD_SUPPLY_INFO_AMOUNT) {
        return this.$message.warning(`当前单据提交的行数不能超过${ADD_SUPPLY_INFO_AMOUNT}`)
      }
      let apiUrl =
        '/sysback/supplyskurel/batchCreateSupplySkuRel?batchState=prepareing';
      let data = this.specTableData;
      data.forEach((item, index) => {
        item.isMainSupply = '1';
        item.supplyUuid = this.supplyUuid;
      });
      this.submitLoading = true;
      ApiRequest(apiUrl, 'post', data, false)
        .then(res => {
          this.submitLoading = false;
          if (res.retStatus == '1') {
            this.$Message.success('保存成功');
            this.$router.push({ name: 'commodityNotPerfection' }); // 跳转待准入页面
          }
        })
        .catch(() => {
          this.submitLoading = false;
        });
    }
  }
};
</script>
<style lang="less" scoped>
.ivu-table-wrapper {
  overflow: visible;
}
</style>
